﻿using System.Diagnostics;
using System.IO;

using Microsoft.ApplicationBlocks.Updater;

namespace DotUpdater.ActivationProcessors
{
    /// <summary>
    /// Command line processor that will install an msi in the system.
    /// </summary>
    public sealed class MsiCmdlineProcessor : IActivationProcessor
    {
        private string _file;

        #region IActivationProcessor Members

        public void Init(IUpdaterTask task)
        {
            if (task.Files.Length != 1) 
                throw new ApplicationUpdaterException("Only 1 file per task supported now: " + task);

            _file = Path.Combine(task.DownloadFilesBase, task.Files[0]);

            if (!File.Exists(_file)) 
                throw new ApplicationUpdaterException("File not found: " + _file);
        }

        void IActivationProcessor.PrepareExecution()
        {
        }

        void IActivationProcessor.Execute()
        {
            // execute the msiexec application forcing it to reinstall the pacakge.
            using (var installUtilProcess = new Process())
            {
                installUtilProcess.StartInfo.FileName = "msiexec";
                installUtilProcess.StartInfo.Arguments = 
                    string.Format("/qb /i {0} REINSTALL=ALL REINSTALLMODE=vomus", _file);
                installUtilProcess.Start();
            }
        }

        void IActivationProcessor.OnError()
        {
        }

        #endregion
    }
}
